package com.hh.baseframework.util.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.hh.baseframework.util.dto.PageRange;
import com.hh.hibernate.util.base.BaseOneEntity;

@SuppressWarnings("serial")
public class BaseAction<T extends BaseOneEntity> extends BaseServletAction {
	private Map<String, Object> resultMap = new HashMap<String, Object>();
	private Gson gson = new Gson();

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public void setResultMap(Map<String, Object> resultMap) {
		this.resultMap = resultMap;
	}

	public Gson getGson() {
		return gson;
	}

	public void setGson(Gson gson) {
		this.gson = gson;
	}


	public void returnResult(Object... objects) {
		try {
			PrintWriter out = this.getResponse().getWriter();
			if (objects.length == 0) {
				resultMap.put("success", true);
				out.print(gson.toJson(resultMap));
			} else {
				for (Object object2 : objects) {
					out.print(gson.toJson(object2));
				}
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分页模版
	 */
	public PageRange getPageRange() {
		PageRange pageRange = new PageRange(this.getPage(), this.getStart(),
				this.getLimit());
		return pageRange;
	}

	// 第几页
	private int page;
	// 第几条数据开始
	private int start;
	// 每页显示多少条
	private int limit;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	private String ids;

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	/**
	 * 参数Map
	 */
	protected Map<String, String> paramsMap = new HashMap<String, String>();

	public Map<String, String> getParamsMap() {
		return paramsMap;
	}

	public void setParamsMap(Map<String, String> paramsMap) {
		this.paramsMap = paramsMap;
	}

	public Class getGenericType(int index) {
		Type genType = getClass().getGenericSuperclass();
		if (!(genType instanceof ParameterizedType)) {
			return Object.class;
		}
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		if (index >= params.length || index < 0) {
			throw new RuntimeException("Index outof bounds");
		}
		if (!(params[index] instanceof Class)) {
			return Object.class;
		}
		return (Class) params[index];
	}

}
